package api

import (
	"github.com/gin-gonic/gin"
	"go-programming-tour-book/blog-service/global"
	"go-programming-tour-book/blog-service/internal/service"
	"go-programming-tour-book/blog-service/pkg/app"
	"go-programming-tour-book/blog-service/pkg/errcode"
	"net/http"
)

type Auth struct {
}

func NewAuth() Auth {
	return Auth{}
}

func (a Auth) GetAuth(c *gin.Context) {
	param := service.AuthRequest{}

	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)

	if !valid {
		global.Logger.Fatalf("bindvalue fail:$v", errs)

		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)

		response.ToErrorResponse(errRsp)

		return
	}

	svc := service.New(c.Request.Context())

	err := svc.CheckAuth(&param)

	if err != nil {
		global.Logger.Fatalf("checkAuth is fail:$v", err)

		response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)

		return
	}

	token, err := app.GenerateToken(param.AppKey, param.AppSecret)

	if err != nil {
		global.Logger.Fatalf("token is fail:$v", err)

		response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)

		return
	}

	response.ToResponse(gin.H{
		"code":  http.StatusOK,
		"msg":   "成功",
		"token": token,
	})
}
